//
//  MainTabBarController.swift
//  HuaYun
//
//  Created by enghou on 2018/7/10.
//  Copyright © 2018年 xyxorigation. All rights reserved.
//

import UIKit

class MainTabBarController: UITabBarController {

    @objc func callLogin()->Void{
        
        let login = LoginViewController()
        
        let navi = UINavigationController.init(rootViewController: login)
        
        self.present(navi, animated: true, completion: nil)
        
    }
    
    override var shouldAutorotate: Bool{
        get{
            return self.selectedViewController?.shouldAutorotate ?? false
        }
    }
    
    override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation{
        get{
            return self.selectedViewController?.preferredInterfaceOrientationForPresentation ?? .portrait
        }
    }
    
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask{
        get{
            return self.selectedViewController?.supportedInterfaceOrientations ?? .portrait
        }
    }
    
    var types: [JSON] = []
    override func viewDidLoad() {
        super.viewDidLoad()
        
        NetManager.get(ComprehensivePlanType, nil, suc: { (json) in
            self.types = json["data"].array ?? []
        }) { (error) in
            
        }
        UITabBarItem.appearance().setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.mainColor], for: .selected)
        
        if User.id.count > 0 {
            JPUSHService.setAlias(User.id, completion: { (code, str, res) in
                
            }, seq: 1)
        }
        
//        NotificationCenter.default.addObserver(self, selector: #selector(refreshbadge), name: NSNotification.Name.init(rawValue: "REFRESHBADGE"), object: nil)
//        NotificationCenter.default.addObserver(self, selector: #selector(refreshbadge), name: Notification.Name.init("RefreshDetail"), object: nil)
        
        NotificationCenter.default.addObserver(self, selector: #selector(callLogin), name: NSNotification.Name("NeedLogin"), object: nil)
        
        for item in self.tabBar.items! {
            
            item.image = item.image?.withRenderingMode(.alwaysOriginal)
            
            item.selectedImage = item.selectedImage?.withRenderingMode(.alwaysOriginal)
        }
        
        refreshbadge()
        self.update()
    }
    
    
    @objc func update(){
        refreshbadge()
        if self.presentedViewController == nil {
            let task = URLSession.shared.downloadTask(with: URL.init(string: "https://tms.hyit.com.cn/tasktracking/manifest.plist")!) { (url, response, error) in
                if error == nil {
                    do {
                        
                        if let dictionary = NSDictionary.init(contentsOf: url!) {
                            let items = JSON(dictionary)
                            let versionstr = items["items"][0]["metadata"]["bundle-version"].string ?? "0.0"
                            let version = Double.init(versionstr) ?? 0.0
                            let infoDictionary = Bundle.main.infoDictionary
                            let currentversionstr = infoDictionary?["CFBundleShortVersionString"] as! String
                            let currentversion = Double.init(currentversionstr) ?? 1.0
                            if currentversion < version {
                                DispatchQueue.main.async {
                                    let alert = UIAlertController.init(title: "发现新的版本", message: "请点击更新", preferredStyle: .alert)
                                    let action1 = UIAlertAction.init(title: "确定", style: .default, handler: { (_) in
                                        UIApplication.shared.openURL(URL.init(string: "itms-services://?action=download-manifest&url=https://tms.hyit.com.cn/tasktracking/manifest.plist")!)
                                    })
                                    alert.addAction(action1)
                                    JumpHelper.shared.topmost?.present(alert, animated: true, completion: nil)
                                }
                            }
                        }
                    }
                }
            }
            task.resume()
        }
    }
    
    func currentvc() -> UIViewController {
        var window = UIApplication.shared.keyWindow
        if window?.windowLevel != UIWindow.Level.normal {
            let windows = UIApplication.shared.windows
            for tmpWin in windows {
                if tmpWin.windowLevel == UIWindow.Level.normal {
                    window = tmpWin
                    break
                }
            }
        }
        let view = window?.subviews.first
        let responder = view?.next
        if responder is UIViewController {
            return responder as! UIViewController
        } else {
            return window!.rootViewController!
        }
    }
    
    @objc func refreshbadge()->Void{
        NetManager.get(NeedHandleCount, nil, suc: { (json) in
            if let success = json.contents?["success"]?.bool {
                if success == true {
                    if let data = json.contents?["data"]?.int {
                        if data > 0 {
                            self.tabBar.items![1].badgeValue = String(data)
                        } else {
                            self.tabBar.items![1].badgeValue = nil
                        }
                    }
                }
            }
        }) { (err) in
            
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
